package com.lw.leetcode.stack.c;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * stack
 * 224. 基本计算器
 *
 * @author liw
 * @version 1.0
 * @date 2021/11/26 20:50
 */
public class Calculate {


    public static void main(String[] args) {
        Calculate test = new Calculate();

        //-87
//        String str = "(1-(4-(6-(5+4)-90)+2)-3)+(6+8)";

        // -12
        String str = "- (3 + (4 + 5))";

        int calculate = test.calculate(str);
        System.out.println(calculate);
    }


    public int calculate(String s) {
        Stack<Integer> stack = new Stack<>();
        char[] arr = s.toCharArray();
        int length = s.length();
        int sum = 0;
        int item = 0;
        stack.add(0);
        int lastOp = 0;
        int op = 0;
        for (int i = 0; i < length; i++) {
            char ch = arr[i];
            if (ch >= '0' && ch <= '9') {
                int cur = ch - '0';
                while (i + 1 < length && Character.isDigit(arr[i + 1])) {
                    cur = cur * 10 + arr[++i] - '0';
                }
                sum += lastOp == 0 ? cur : -cur;
            } else if (ch == '+') {
                lastOp = item;
                op = 0;
            } else if (ch == '-') {
                lastOp = 1 ^ item;
                op = 1;
            } else if (ch == '(') {
                stack.add(op);
                item = stack.peek() ^ item;
            } else if (ch == ')') {
                item = item ^ stack.pop();
            }
        }
        return sum;
    }

}
